package com.yuyang.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuyang.common.exception.BizCodeEnum;
import com.yuyang.common.utils.HttpUtils;
import com.yuyang.common.utils.PageUtils;
import com.yuyang.common.utils.Query;
import com.yuyang.common.utils.R;
import com.yuyang.gulimall.member.dao.MemberDao;
import com.yuyang.gulimall.member.entity.MemberEntity;
import com.yuyang.gulimall.member.entity.MemberLevelEntity;
import com.yuyang.gulimall.member.exception.PhoneExistException;
import com.yuyang.gulimall.member.exception.UserNameExistException;
import com.yuyang.gulimall.member.service.MemberLevelService;
import com.yuyang.gulimall.member.service.MemberService;
import com.yuyang.gulimall.member.to.SocialUser;
import com.yuyang.gulimall.member.to.UserLoginTo;
import com.yuyang.gulimall.member.to.UserRegisterTo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(UserRegisterTo userRegisterTo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity one = memberLevelService.getOne(new LambdaQueryWrapper<MemberLevelEntity>().eq(MemberLevelEntity::getDefaultStatus, 1));
        //默认会员等级
        memberEntity.setLevelId(one.getId());
        String phone = userRegisterTo.getPhone();
        long count = this.count(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getMobile, phone));
        if (count > 0) {
            throw new PhoneExistException("该手机号已经被注册");
        }
        String userName = userRegisterTo.getUserName();
        if (this.count(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, userName)) > 0) {
            throw new UserNameExistException("该用户名已经被注册");
        }
        memberEntity.setUsername(userName);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(userRegisterTo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setMobile(phone);
        this.save(memberEntity);
    }

    @Override
    public MemberEntity login(UserLoginTo to) {
        MemberEntity memberEntity = this.getOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, to.getLoginAccount()).
                or().eq(MemberEntity::getMobile, to.getLoginAccount()));
        if (memberEntity == null){
            return null;
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(to.getPassword(), memberEntity.getPassword());
        if (!matches) {
            return null;
        }
        return memberEntity;
    }

    @Override
    public MemberEntity weiboLogin(SocialUser to) {
        MemberEntity memberEntity = this.getOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getSocialUid, to.getUid()));
        //社交登录过
        if (memberEntity != null){
            memberEntity.setAccessToken(to.getAccess_token());
            memberEntity.setExpiresIn(to.getExpires_in());
            this.updateById(memberEntity);
        }else {
            //第一次登录注册新账号
            memberEntity = new MemberEntity();
            MemberLevelEntity one = memberLevelService.getOne(new LambdaQueryWrapper<MemberLevelEntity>().eq(MemberLevelEntity::getDefaultStatus, 1));
            //默认会员等级
            memberEntity.setLevelId(one.getId());
            memberEntity.setAccessToken(to.getAccess_token());
            memberEntity.setExpiresIn(to.getExpires_in());
            memberEntity.setSocialUid(to.getUid());
            HashMap<String, String> map = new HashMap<>();
            map.put("access_token",to.getAccess_token());
            map.put("uid",to.getUid());
            try {
                //获取用户微博的信息
                HttpResponse httpResponse = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(httpResponse.getEntity()));
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    memberEntity.setUsername(name);
                    memberEntity.setNickname(name);
                    memberEntity.setGender("m".equals(gender)?1:0);
                }
            } catch (Exception e) {}
            this.save(memberEntity);

        }
        return memberEntity;
    }


}